import { withRouter } from "next/router";
import { useState, useEffect } from "react";
import { Rate, Upload, Input, Button, message } from "antd";
import { PlusOutlined } from '@ant-design/icons';
import Cookies from "js-cookie";
// css
import styles from "@/styles/CommonPersonal.module.scss";
// 组件
import Breadcrumb from "@/components/Breadcrumb";
import Aside from "@/pages_components/personal/Aside";
import Spin from "@/components/Spin";
// api
import { myUploadUrl, myCommentSubmit } from '@/api/personal'

const desc = ["很差", "一般", "满意", "非常满意", "无可挑剔"];

const Comment = ({ router }) => {

  const [goodsName, setGoodsName] = useState("");

  const [loading, setLoading] = useState(false);
  const [path, setPath] = useState("/");
  
  const [level, setLevel] = useState(0);
  const [comment, setComment] = useState('')

  const [uploadUrl, setUploadUrl] = useState('')
  const [fileList, setFileList] = useState([])

  useEffect(() => {

    setGoodsName(Cookies.get('comment_goodsName'))
    
    setPath(router.asPath);

    const url = myUploadUrl();
    setUploadUrl(url)

  }, []);

  // 评分
  function rateLevels(v) {
    setLevel(v);
  }
  // 上传图片
  function uploadFile({ fileList }) {
    setFileList(fileList)
  }
  // 提交评价
  function submitComment() {
    if(level <= 0){
        message.warn('请选择满意程度')
        return false
    }
    if(comment.trim().length < 10){
        message.warn('请填写产品评价，不少于10个字')
        return false
    }
    const imgs = fileList.map(item => {
        const { response: { data } } = item;
        return data
    })
    let params = {
        description: comment,
        score: level,
        orderId: router.query.orderId,
        label: "",
        imgUrl: imgs.join(","),
    };
    setLoading(true)
    myCommentSubmit(params).then(res => {
        let { code, data } = res;
        if (code == 0 && data) {
          message.success('已提交评价');
          router.push("/personal/order");
        }
        setLoading(false)
    })
  }

  return (
    <div className={styles["personal-page"]}>
      {/* loading */}
      <Spin loading={loading} />
      <div className="max-content">
        {/* 面包屑 */}
        <Breadcrumb
          params={[
            { name: "个人中心", url: "/personal" },
            { name: "发表评价", url: path },
          ]}
        />
        <div className={styles["wrapper"]}>
          {/* 左侧 */}
          <Aside />
          {/* 内容 */}
          <section className={[styles["content"], styles["comment-content"]].join(" ")} >
            <div className={styles['max-comment']}>
                <h3>{goodsName}</h3>
                <div className={styles['form-item']}>
                    <p>满意程度</p>
                    <Rate tooltips={desc} onChange={rateLevels} value={level} />
                    {level ? <span className={styles['form-item-rate']}>{desc[level - 1]}</span> : ""}
                </div>
                <div className={styles['form-item']}>
                    <p>产品评价</p>
                    <Input.TextArea 
                      rows={8} 
                      onChange={(e) => setComment(e.target.value) } 
                      placeholder="需要简述您的问题和建议（至少10个字）"
                    />
                </div>
                <div className={styles['form-item']}>
                  <Upload
                      listType="picture-card"
                      accept=".png, .jpg, .jpeg"
                      name="multipartFile"
                      action={uploadUrl}
                      multiple={true}
                      fileList={fileList}
                      onChange={uploadFile}
                  >
                    <div>
                        <PlusOutlined />
                        <div style={{ marginTop: 8 }}>上传图片</div>
                        <div>(选填)</div>
                    </div>
                  </Upload>
                </div>
                <div className={styles['form-item']}>
                    <Button type="primary" onClick={() => {submitComment()}}>提交评价</Button>
                </div>
            </div>
          </section>
        </div>
      </div>
    </div>
  );
};

export default withRouter(Comment);
